import { Effect, Subscription } from 'dva';
import { Reducer } from 'redux';
import { depts } from '@/services/boss';
import { TreeNodeNormal } from 'antd/lib/tree/Tree';

export interface DeptStateType {
  data: Array<TreeNodeNormal>;
}

interface DeptModelType {
  namespace: 'depts';
  state: DeptStateType;
  reducers: {
    saveDepts: Reducer<DeptStateType>;
  };
  effects: {
    fetchDepts: Effect;
  };
  subscriptions: {
    setup: Subscription;
  };
}

const DeptModel: DeptModelType = {
  namespace: 'depts',
  state: { data: [] },
  reducers: {
    saveDepts(state = { data: [] }, { payload }) {
      return {
        data: [...payload.data],
      };
    },
  },
  effects: {
    *fetchDepts(_, { put, call }) {
      let data: DeptStateType = yield call(depts, {});
      yield put({ type: 'saveDepts', payload: data });
    },
  },
  subscriptions: {
    setup({ history, dispatch }) {
      history.listen(location => {
        if (location.pathname == '/boss/list') {
          dispatch({
            type: 'fetchDepts',
          });
        }
      });
    },
  },
};

export default DeptModel;
